package com.phoenix.sgs.faq;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.phoenix.sgs.faq.R.string;
import com.phoenix.sgs.faq.db.DBHelper;
import com.phoenix.sgs.faq.meta.KeyValuePair;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GeneralListActivity extends ListActivity  {
	private ProgressDialog progressDialog = null; 
	private Runnable queryData;
	private ArrayAdapter<KeyValuePair> adapter;
	List<KeyValuePair> generals;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        progressDialog = ProgressDialog.show(this, "Loading...", "Please wait...", true, false);
        
        new Thread() {
        	@Override
        	public void run() {
        		generals = getGenerals();
        		handler.sendEmptyMessage(0);
        	}
        }.start();
		
    }
    
    private Handler handler = new Handler() {
    	@Override  
    	public void handleMessage(Message msg) {  
    		//关闭ProgressDialog  
    		progressDialog.dismiss();  

    		//更新UI  
    		bindList();
    	}
    };
    
    private void bindList() {
    	adapter = new ArrayAdapter<KeyValuePair>(
				this, 
				R.layout.generallist, 
				generals.toArray(new KeyValuePair[generals.size()]));
        setListAdapter(adapter);

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(
        		AdapterView<?> parent, 
        		View view,
        		int position, 
        		long id) {
        		KeyValuePair selectedItem = adapter.getItem(position);
        		openGeneralDetail(selectedItem);
        	}
        });
    }
    
    private void openGeneralDetail(KeyValuePair selectedItem) {
		Intent intent = new Intent(this, GeneralDetailActivity.class);
		intent.putExtra("SelectedId", selectedItem.getKey());
    	startActivity(intent);
    }
    
    private List<KeyValuePair> getGenerals() {
    	SQLiteDatabase db = null;
        Cursor cursor = null;
        List<KeyValuePair> generals = new ArrayList<KeyValuePair>();
        
        try {
        	Intent intent = this.getIntent();
        	int queryMethod = intent.getIntExtra("QueryMethod", 0);
        	int selectedId = intent.getIntExtra("SelectedId", 0);
        	String sql = this.getSQL(queryMethod, selectedId);
        	
			DBHelper dbHelper = new DBHelper(this);
			db = dbHelper.openDatabase();
			cursor = db.rawQuery(sql, null);
			if (cursor == null) {
				return generals;
			}
		    
			int numColumn_id = cursor.getColumnIndex("Id");
			int numColumn_name = cursor.getColumnIndex("Name");
			int numColumn_alias = cursor.getColumnIndex("Alias");
			
			if (cursor.moveToFirst()) {
				do {
					int id = cursor.getInt(numColumn_id);
					String name = new String(cursor.getBlob(numColumn_name), "GBK").trim();
					String alias = new String(cursor.getBlob(numColumn_alias), "GBK").trim();
					generals.add(new KeyValuePair(id, alias + " - " + name));
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			if (db != null) {
				db.close();
			}
		}
		
		return generals;
    }
    
    private String getSQL(int queryMethod, int selectedId) {
    	String sql = "SELECT * FROM Generals";
    	if (queryMethod == string.query_method_bypackage) {
    		sql = sql + " WHERE PackageId = " + selectedId;
    	} else if (queryMethod == string.query_method_bycountry) {
    		sql = sql + " WHERE CountryId = " + selectedId;
    	}
    	
    	return sql;
    }
}
